import { getCartList, addToCart, subGoodsCart } from '@/api/cart'

export default {
  namespaced: true,
  state () {
    return {
      cartlist: [],
      carttotal: 0,
      checkedId: []
      // checkState: []
    }
  },
  mutations: {
    getcartlist (state, result) {
      state.cartlist = result.list
      state.carttotal = result.cartTotal
    },

    changeCheckState (state, obj) {
      state.cartlist[obj.index].isChecked = !obj.sta
      // state.checkState[obj.index] = !obj.sta
    },
    changeNum (state, obj) {
      const goods = state.cartlist.find(item => item.goods_id === obj.id)
      goods.goods_num = obj.num
    },
    toggleCheck (state, id) {
      const goods = state.cartlist.find(item => item.goods_id === id)
      goods.isChecked = !goods.isChecked
    },
    toggleCheckAll (state, ischeck) {
      state.cartlist.forEach(item => {
        if (ischeck) {
          item.isChecked = true
        } else {
          item.isChecked = false
        }
      })
    },
    subChecked (state) {
      state.checkedId = state.cartlist.filter(item => item.isChecked).map(item => item.id)
    }
  },
  actions: {
    async getresult (context) {
      const result = await getCartList()
      result.data.list.forEach((e, index) => {
        e.isChecked = true
        // context.state.checkState[index] = e.isChecked
      })

      context.commit('getcartlist', result.data)
    },
    async changeCart (context, obj) {
      const result = await addToCart(obj.id, obj.num, obj.skuid)
      console.log(result)

      context.commit('changeNum', obj)
    },

    async delGoods (context) {
      console.log(context.state.checkedId)

      const result = await subGoodsCart(context.getters.subChecked)
      console.log(result)
    }
  },
  getters: {
    totalPrice (state) {
      return state.cartlist.filter(item => {
        return item.isChecked === true
      }).reduce((sum, item) => {
        sum += item.goods_num * item.goods.goods_price_min
        return sum
      }, 0)
    },
    subChecked (state) {
      return state.cartlist.filter(item => item.isChecked).map(item => item.id)
    },
    selCheckedGoods (state) {
      return state.cartlist.filter(item => item.isChecked)
    }

  }
}
